package com.wzdigit.wms.raw.service.mid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.client.response.basic.SkuBaseResponse;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.TransferDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.TransferHeaderMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.raw.constant.SyncTypeConstant;
import com.wzdigit.wms.raw.domain.dto.HouseQaStatus;
import com.wzdigit.wms.raw.domain.dto.IfRawtransferHeaderDto;
import com.wzdigit.wms.raw.domain.mid.IfRawtransferDtl;
import com.wzdigit.wms.raw.domain.mid.IfRawtransferHeader;
import com.wzdigit.wms.raw.exception.SyncException;
import com.wzdigit.wms.raw.mapper.mid.IfRawtransferDtlMapper;
import com.wzdigit.wms.raw.mapper.mid.IfRawtransferHeaderMapper;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-送货单 同步 收货单
 * </p>
 *
 * @author chao shuai
 * @since 2021-03-16
 */
@Service
public class IfRawTransferHeaderService {

    @Autowired
    private IfRawtransferHeaderMapper ifRawtransferHeaderMapper;

    @Autowired
    private IfRawtransferDtlMapper ifRawtransferDtlMapper;

    @Autowired
    private TransferHeaderMapper rawtransferHeaderMapper;

    @Autowired
    private TransferDtlMapper rawtransferDtlMapper;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi  basicVendorApi;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    CodeMappingService codeMappingService;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;


    @Autowired
    AsnDtlMapper asnDtlMapper;
    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;

    @Autowired
    private  MappingHouseService mappingHouseService;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;
    
    private final String syncType = SyncTypeConstant.IF_ASN_TO_ASN;

    public List<IfRawtransferHeaderDto> selectSyncData() {
        ArrayList<IfRawtransferHeaderDto> ifRawtransferHeaderDtos = new ArrayList<>();
        QueryWrapper<IfRawtransferHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        List<IfRawtransferHeader> selectSyncData = ifRawtransferHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfRawtransferHeader ifRawtransferHeader : selectSyncData) {
                IfRawtransferHeaderDto ifRawtransferHeaderDto = new IfRawtransferHeaderDto();
                BeanUtil.copyNonNull(ifRawtransferHeader, ifRawtransferHeaderDto);
                List<IfRawtransferDtl> ifSalesreturnDtls = ifRawtransferDtlMapper.selectList(new QueryWrapper<>(
                        new IfRawtransferDtl().setIfRawtransferHeaderId(ifRawtransferHeader.getIfRawtransferHeaderId())
                ));
                ifRawtransferHeaderDto.setIfRawtransferDtlList(ifSalesreturnDtls);
                ifRawtransferHeaderDtos.add(ifRawtransferHeaderDto);
            }

        }
        return ifRawtransferHeaderDtos;
    }



    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncData(IfRawtransferHeaderDto data, boolean isSyncError) throws Exception {
        String rawtransferNumber = ""; //原材料入库单
        Long  transferRef2 = null;//参考信息2
        if("1".equals(data.getZtype())){//调拨单
            rawtransferNumber = data.getMblnr();
            transferRef2 = data.getMjahr();
        }else if("2".equals(data.getZtype())){ //盘点过帐单
            rawtransferNumber = data.getIblnr();
            transferRef2 = data.getGjahr();
        }else{
            throw new SyncException(syncType, rawtransferNumber, "无法处理的单据类型==》"+data.getZtype());
        }
        IfRawtransferDtl dtl = data.getIfRawtransferDtlList().get(0);
        AsnHeader asnHeader = new AsnHeader();
        //同步主表信息

        asnHeader.setAsnNo(rawtransferNumber);
        asnHeader.setFactory(dtl.getWerks());//工厂
        asnHeader.setAsnType(AsnTypeEnum.R21.code);//采购入库
        asnHeader.setReleaseStatus(1);
        asnHeader.setAsnCreateUser(data.getCreateUser());
        asnHeader.setAsnCreateTime(data.getCreateTime());
        asnHeader.setQcStatus( QcStatusEnum.全部质检.getCode());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0: Integer.valueOf(dataItem.getItemValue()));
        AsnHeader asnHeaderRecord = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(rawtransferNumber)));
        if (asnHeaderRecord == null) {
            asnHeader.setCreateTime(new Date());
            asnHeader.setStatus( AsnHeaderStatusEnum.CREATE.getCode());//新建状态

            asnHeader.setCreateTime(data.getCreateTime());
            asnHeader.setCreateUser(data.getCreateUser());

            asnHeaderMapper.insert(asnHeader);
        } else {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeader.setAsnHeaderId(asnHeaderRecord.getAsnHeaderId());
            asnHeader.setAsnNo(asnHeaderRecord.getAsnNo());
            asnHeaderMapper.updateById(asnHeader);
        }
        //同步明细


        for (IfRawtransferDtl ifRawtransferDtl : data.getIfRawtransferDtlList()) {
            //查询SKUID ；
            SkuBaseResponse sku = skuMapper.getSkuByCode(ifRawtransferDtl.getMatnr());
            if(sku==null||sku.getSkuId()==null){
                throw new SyncException(syncType, rawtransferNumber, "物料编码" + ifRawtransferDtl.getMatnr() + "不存在");
            }
            //获取仓库
            HouseQaStatus houseQaStatus = mappingHouseService.getWmsHourseIdBySapHourseCode(data.getUmlgo());
            if(houseQaStatus==null){
                throw new SyncException(syncType, rawtransferNumber, "SAP仓库编码" + data.getUmlgo() + "无法转换成WMS仓库");
            }


            AsnDtl asnDtl = new AsnDtl();

            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setAsnNo(asnHeader.getAsnNo());
            //根据不同类型取对应行号
            String lineNo = ifRawtransferDtl.getZeili();
            asnDtl.setAsnLineNo(lineNo);
            asnDtl.setSkuId(sku.getSkuId());//查询SKU
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setUnit(sku.getBaseUnit());
            asnDtl.setWhsId(houseQaStatus.getWhsId());
            asnDtl.setOrderQty(ifRawtransferDtl.getMenge());
            asnDtl.setOrderQtyEa(ifRawtransferDtl.getMenge());
            asnDtl.setQcStatus(QcStatusEnum.全部质检.getCode());
            asnDtl.setQaStatus(QaStatusEnum.OK.code);
            asnDtl.setUdf5(data.getLgort());

            AsnDtl asnDtlRecord = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnNo(asnHeader.getAsnNo()).setAsnLineNo(lineNo)));
            if (asnDtlRecord == null) {
                asnDtl.setCreateUser("system");
                asnDtl.setCreateTime(new Date());
                asnDtl.setStatus( AsnDtlStatusEnum.CREATE.getCode());//新建状态

                try {
                    asnDtlMapper.insert(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, rawtransferNumber, e.getMessage());
                }
            } else {
                asnDtl.setModifyUser("system");
                asnDtl.setModifyTime(new Date());
                asnDtl.setAsnDtlId(asnDtlRecord.getAsnDtlId());
                try {
                    asnDtlMapper.updateById(asnDtl);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, rawtransferNumber, e.getMessage());
                }
            }
            int row = ifRawtransferHeaderMapper.updateFlagById(data.getIfRawtransferHeaderId());
            //检查是否有同步失败的记录，有则更新为成功
            JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, rawtransferNumber);
            if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
                syncErrorDataService.updateSuccessByCode(syncType, rawtransferNumber);
            }
        }

    }


}
